package com.science.slam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.science.slam.domain.User;
import com.science.slam.exception.BusinessException;
import com.science.slam.exception.ErrorCode;
import com.science.slam.service.UserService;
import com.science.slam.mapper.UserMapper;
import com.science.slam.utils.PasswdUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    UserMapper userMapper;

    @Override
    public Integer addUserFileNumByAccount(String account) {
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("account", account);
        String sql = "file_number = file_number + 1";
        userUpdateWrapper.setSql(sql);
        return userMapper.update(null, userUpdateWrapper);
    }

    @Override
    public User selectByPhoneNumber(String phoneNumber) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone_number", phoneNumber);
        return userMapper.selectOne(userQueryWrapper);
    }

    @Override
    public Integer editUserMessage(String account, String colName, Object newMessage) {
        if (colName.equals("passwd"))
            return editPasswd(account, newMessage);
        if (colName.equals("account") || colName.equals("createTime"))
            throw new BusinessException(ErrorCode.CANNOT_EDIT);
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.set(colName, newMessage).eq("account", account);
        return userMapper.update(userUpdateWrapper);
    }

    @Override
    public User selectByAccount(String account) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.eq("account", account);
        return userMapper.selectOne(userQueryWrapper);
    }

    @Override
    public User getCurrentUser(HttpServletRequest request) {
        return ((User) request.getSession().getAttribute("LOGIN_USER"));
    }

    @Override
    public Boolean checkSubmitAuthorization(User user) {
        if (user.getIsAdmin() == 1 || user.getIsVip() == 1)
            return true;
        if (user.getFileNumber() >= UserService.NORMAL_USER_MAX_FILE_NUM)
            return false;
        return true;
    }

    private Integer editPasswd(String account, Object passwd) {
        String s = PasswdUtils.SHA1(((String) passwd));
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.set("passwd", s).eq("account", account);
        return userMapper.update(userUpdateWrapper);
    }
}




